package com.wuseguang.springcloud.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.wuseguang.springcloud.JdbcTemplate.WXJdbc;
import com.wuseguang.springcloud.dao.jdbc.ActivityJdbc;
import com.wuseguang.springcloud.dao.repository.ActivityRepository;
import com.wuseguang.springcloud.dao.repository.EnrolledStudentsRepository;
import com.wuseguang.springcloud.entity.Activity;
import com.wuseguang.springcloud.entity.EnrolledStudents;
import com.wuseguang.springcloud.service.ActivityService;
import com.wuseguang.springcloud.util.*;
import com.wuseguang.springcloud.util.WeChat.TemplateTools;
import com.wuseguang.springcloud.util.WeChat.WXUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 活动表 服务实现类
 * </p>
 *
 * @author 
 * @since 2020-05-11
 */
@Service
public class ActivityServiceImpl  implements ActivityService {

    private Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private ActivityJdbc activityJdbc;
    @Autowired
    private ActivityRepository activityRepository;
    @Autowired
    private EnrolledStudentsRepository enrolledStudentsRepository;
    @Autowired
    private WXJdbc wXJdbc;

    @Override
    public Result findActivity(String title, String teacherId, Integer indexNo, Integer rows) {

        logger.info("查询教师发布的所有活动 ActivityServiceImpl-> findActivity  title={}",title);
        //查询活动报名数据
        String  sql = "select id,teacher_id,title,DATE_FORMAT(activity_start_time,'%Y-%m-%d %T') activity_start_time " +
                ",DATE_FORMAT(activity_end_time,'%Y-%m-%d %T') activity_end_time," +
                " DATE_FORMAT(enrollment_start_time,'%Y-%m-%d %T')enrollment_start_time," +
                "  DATE_FORMAT(enrollment_end_time,'%Y-%m-%d %T') enrollment_end_time," +
                " highlights,activity_content,quota,cost,url,add_time,signed_up ," +
                " (CASE WHEN NOW() > a.activity_end_time THEN 5 " +
                " WHEN NOW() < a.activity_end_time and NOW() >= a.activity_start_time THEN 4  " +
                " WHEN NOW() < a.enrollment_start_time THEN 0 " +
                " WHEN NOW() > a.enrollment_end_time THEN 2  " +
                " WHEN a.state = 3 THEN 3 ELSE 1 END ) state " +
                "  from activity a where " +
                "a.teacher_id = ? ";

        List<Map<String,Object>> list = null;

        //判断查询名称是否为空
        if(!StringUtils.isEmpty(title)){
            sql+=" and a.title LIKE ? ORDER BY id desc ";
            list = activityJdbc.queryListMap(sql,teacherId,title);
        }else{
            sql+=" ORDER BY id desc ";
            list = activityJdbc.queryListMap(sql,teacherId);
        }

        //创建分页工具
        PagingTool tool = new PagingTool();
        //放入页码
        tool.setIndexNo(indexNo);
        //放入每页显示数量
        tool.setRows(rows);
        //放入角色集合
        tool.setList(list);
        //返回数据
        return new Result(new PaginationUtil<>(list.size(), rows, tool.getList(), indexNo));
    }

    @Override
    public Result addActivity(Activity activity) {


        logger.info("教师添加活动 ActivityServiceImpl-> addActivity  ");
        activity.setAddTime(new Date());
        activity.setSignedUp(0);
        //获取活动id
        Integer id = activityRepository.save(activity).getId();


        //获取所有班级
        String [] classIds =  activity.getClassId().split(",");
        //查询学生的信息
        for (int i = 0 ; i < classIds.length ; i++){
            //查询添加
            String sql = "INSERT INTO enrolled_students (activity_id, student_id,state)" +
                    " select ?,id,0 from student where class_id = ?";
            activityJdbc.updateByParameter(sql,id,classIds[i]);

            //添加通知
            sql = "INSERT INTO `all_notice`" +
                    " (`jurisdiction_id`, `type`, `content`, `class_id`," +
                    " `teacher_id`, `student_id`, `school_id`, `papplet`, `opertime`) " +
                    "select 109, 9, '老师发布一条最新的活动，请查看。', ?, ?, id, ?, 1, NOW() from student where class_id = ?";
            activityJdbc.updateByParameter(sql,classIds[i],activity.getTeacherId(),activity.getSchoolId(),classIds[i]);
            //添加通知未查看记录
            sql = "INSERT INTO notice_see(jurisdiction_id,student_id,type,add_time) select 109,id,0,now() from student where class_id = ?";
            activityJdbc.updateByParameter(sql,classIds[i]);
        }


        return new Result();
    }

    @Override
    public Result findEnrolledStudentByActivityId(Integer id, String classId, Integer quota) {
        //返回的对象
        Map<String,Object> resultMap = new HashMap<>();
        logger.info("查询活动报名详情 ActivityServiceImpl-> addActivity  ");
        //查询已报名的学生
        String sql = "select es.id ,DATE_FORMAT(es.registration_time,'%Y-%m-%d %T')registration_time,s.student_name,s.head_portrait " +
                "from enrolled_students es LEFT JOIN student s on(es.student_id=s.id) " +
                "where es.state= ? and es.activity_id = ? and s.id is not null "+(StringUtils.isEmpty(classId)? ""
                :" and s.class_id = "+classId);
        //已报名的学生呢
        List<Map<String,Object>> signedUpList = activityJdbc.queryListMap(sql,1,id);
        //未报名
        List<Map<String,Object>> notRegisteredList = activityJdbc.queryListMap(sql,0,id);

        //查询应该报名的学生
        sql = "select COUNT(1) count from enrolled_students es LEFT JOIN student s on(es.student_id=s.id) where es.activity_id = ? and s.id is not null";
        Integer count = activityJdbc.queryCount(sql,id);

        //学生总人数
        resultMap.put("studentTotal",signedUpList.size()+notRegisteredList.size());
        resultMap.put("signedUpList",signedUpList);
        resultMap.put("notRegisteredList",notRegisteredList);
        resultMap.put("signedUpListTotal",signedUpList.size());
        resultMap.put("surplus",quota == 0 ?
                count-signedUpList.size()+"/"+count:
                quota-signedUpList.size()+"/"+quota );

        return new Result(resultMap);
    }

    @Override
    public Result deleteActivityId(Integer id) {
        logger.info("删除活动 ActivityServiceImpl-> deleteActivityId  ");
        //活动信息
        Activity a = activityRepository.findById(id).get();
        //获取当前时间时间戳
        long time = System.currentTimeMillis();
        //
        if(time > a.getActivityStartTime().getTime() && time < a.getActivityEndTime().getTime()){
            //活动已开始不可删除
            return new Result(CodeUtil.ACTIVITY_HAS_STARTED_AND_CANNOT_BE_DELETED);
        }else if(time > a.getEnrollmentStartTime().getTime() && time < a.getEnrollmentEndTime().getTime()){
            //活动已开始报名不可以删除
            return new Result(CodeUtil.ENROLLMENT_HAS_BEEN_OPENED_AND_CANNOT_BE_DELETED);
        }
        activityRepository.deleteById(id);
        enrolledStudentsRepository.deletecByActivityId(id);

        return new Result();
    }

    /**
     * 推送班级的学生信息
     * @param classId 班级id
     */
    public void activityPush(String [] classId,String title ){
        logger.info("活动推送个家长");

        //获取token
        String accessToken = wXJdbc.getOfficialAccountAccessToken(0);
        String sql = "select p.open_id_two from student s " +
                "LEFT JOIN parent_student ps on (s.id=ps.student_id) " +
                "LEFT JOIN parent p on(ps.parent_id=p.id) " +
                "where s.class_id=? and p.open_id_two is not null";
        //循环班级id
        for(int i = 0; i<classId.length;i++){
            //openid
            List<String> openIds = activityJdbc.queryListString(sql,new Object[]{classId[i]});
            //循环这个班级学生家长openId
            for (String openId:openIds) {
                Map<String, Object> pushMap = new HashMap<>();
                pushMap.put("first", "家长您好，教师发布了一条新活动");
                pushMap.put("keyword1", title);
                pushMap.put("keyword2", "日常活动");
                pushMap.put("remark", "感谢您的支持。");

                //跳转小程序信息
                JSONObject appletJson= new JSONObject();
                appletJson.put("appid","wx30b606bac7775eba");
                appletJson.put("pagepath","pages/activity/index");

                //解析后的数据
                JSONObject json = TemplateTools.initializationData(pushMap);
                //推送公众号信息
                WXUtil.officialAccountPush(accessToken, openId, "", "", appletJson, json);
            }
        }


    }

}
